﻿using System;
using System.Collections.Generic;
using Service4u2.Common;
using Service4u2.Json;
using MoAds.AdAdapters;

namespace MoAds.AdAdapters.ZestAdz
{
    /// <summary>
    /// An adapter for showing AdMob ads retrieved via JSON services.
    /// </summary>
    public class ZestAdzAdapter : AdAdapter
    {
        /// <summary>
        /// The AdMob JSON service.
        /// </summary>
        protected ZestAdzService zestAdzService;

        public Int32 AdsPerRequest
        { get; set; }

        /// <summary>
        /// Gets or sets the ad keywords.
        /// </summary>
        /// <value>The ad keywords.</value>
        public string AdKeywords
        { get; set; }

        /// <summary>
        /// Gets or sets the meta data.
        /// </summary>
        /// <value>Meta Data.</value>
        public string MetaData
        { get; set; }

        /// <summary>
        /// Gets or sets the client id.
        /// </summary>
        /// <value>Client Id.</value>
        public string ClientId
        { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="AdMobAdapter"/> class.
        /// </summary>
        public ZestAdzAdapter()
        {
            zestAdzService = new ZestAdzService();
         
            zestAdzService.ResultEvent += new EventHandler<EventArgs<ZestAdzResponse>>(OnResult);
            zestAdzService.ExceptionEvent += new EventHandler<EventArgs<Exception>>(OnException);
        }

        #region AdAdapter Members

        /// <summary>
        /// Handles the GotResult event of the adMobService control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Service4u2.Common.EventArgs&lt;MoAds.AdInfoResponse&gt;"/> instance containing the event data.</param>
        protected virtual void OnResult(object sender, EventArgs<ZestAdzResponse> e)
        {
            AdResponse response = new AdResponse()
            {
                ClickUrl = e.Argument.Url,
            };

            if (!String.IsNullOrEmpty(e.Argument.Text)) response.AdText = e.Argument.Text;
            if (!String.IsNullOrEmpty(e.Argument.Picture)) response.ImageUrl = e.Argument.Picture;

            OnResult(response);
        }

        /// <summary>
        /// Gets the ad response asynchronously.
        /// </summary>
        public override void BeginAdRequestAsync()
        {
            ZestAdzRequest request = new ZestAdzRequest();
            request.Keywords = this.AdKeywords;
            request.MetaData = this.MetaData;
            request.UserAgent = this.BrowserAgentString;
            request.NumberOfAds = this.AdsPerRequest;
            request.ClientId = this.ClientId;
            zestAdzService.BeginAdsAsync(request);
        }

        #endregion
    }
}
